package org.example.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.example.config.OssConfig;
import org.example.service.FileService;
import org.example.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private OssConfig ossConfig;

    /**
     * 用户上传头像
     */
    @Override
    public String uploadUserImage(MultipartFile multipartFile) {
        //1、获取配置基本属性
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();
        //2、获取文件原始名
        String originalFilename = multipartFile.getOriginalFilename();
        //3、获取文件的拓展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //4、获取随机文件名
        String randomFileName = CommonUtil.getUUID();
        //5、获取完整文件名
        String fileName = randomFileName + extension;
        //5、获取日期
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter nowFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //5.1、日期就是文件夹
        String folder = nowFormatter.format(now);
        //6、保存的位置，例如/user/2022/9/26/xxx.jpg
        String newFileName = "user/" + folder + "/" + fileName;
        //7、上传文件
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, newFileName, multipartFile.getInputStream());
            if (putObjectResult != null) {
                String imgUrl = "https://" + bucketName + "." + endpoint + "/" + newFileName;
                return imgUrl;
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            log.error("上传文件失败: {}", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
